package com.example.stupidweather;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.example.stupidweather.gson.Location;
import com.example.stupidweather.gson.Weather;
import com.example.stupidweather.utils.HttpUtil;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.example.stupidweather.utils.Utility.handleWeatherResponse;
import static com.example.stupidweather.utils.Utility.handleLocationResponse;

public class MainActivity extends AppCompatActivity {
    private ScrollView weatherLayout;
    private TextView titleCity;
    private TextView titleUpdateTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayout;
    private String mWeatherId;


    public SwipeRefreshLayout swipeRefresh;


    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化各控件
        swipeRefresh=(SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
        weatherLayout=(ScrollView) findViewById(R.id.weather_layout);
        titleCity=(TextView)findViewById(R.id.title_city);
        titleUpdateTime=(TextView)findViewById(R.id.title_update_time);
        degreeText=(TextView)findViewById(R.id.degree_text);
        weatherInfoText=(TextView)findViewById(R.id.weather_info_text);
        forecastLayout=(LinearLayout)findViewById(R.id.forecast_layout);
        EditText editText=(EditText)findViewById(R.id.edit_text);
        Button button1 = (Button)findViewById(R.id.button1);

        swipeRefresh.setColorSchemeColors(R.color.colorPrimary);
//        String mWeatherId = "101020100";
//        requestWeather(mWeatherId);

        SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString=prefs.getString("weather",null);
        /*String aqiString=prefs.getString("aqi",null);*/

        if(weatherString!=null)
        {
            //有缓存时直接解析天气数据
            Weather weather= (Weather) handleWeatherResponse(weatherString);
            mWeatherId=weather.getHeWeather6().get(0).getBasicX().getCid();
            showWeatherInfo(weather);

        }else
        {   //无缓存时,去服务器查询天气
            //String weatherId=getIntent().getStringExtra("weather_id");
            mWeatherId=getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });

        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String inputText=editText.getText().toString();
                Toast.makeText(MainActivity.this, "当前查询的城市："+inputText, Toast.LENGTH_LONG).show();
                requestLocation(inputText);




            }
        });



    }

    /**
     * 根据天气id请求城市天气信息
     */
    public void requestWeather(String weatherId) {
        final String weatherUrl = "https://free-api.heweather.com/s6/weather?location=" + weatherId.toString() + "&key=5cfa71f0523045cbbc2a915848c89ad4";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "获取天气信息失败onFailure", Toast.LENGTH_LONG).show();
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if ((weather != null) ) {
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();

                            editor.putString("weather", responseText);
                            editor.apply();
                            showWeatherInfo(weather);
                        } else {
                            Toast.makeText(MainActivity.this, responseText, Toast.LENGTH_SHORT).show();

                        }
                        swipeRefresh.setRefreshing(false);
                    }


                });

            }
        });
    }

    /**
     * 根据天气id请求城市天气信息
     */
    public void requestLocation(String cityName) {
        final String locationUrl = "https://geoapi.qweather.com/v2/city/lookup?location="+ cityName +"&key=5cfa71f0523045cbbc2a915848c89ad4";
        HttpUtil.sendOkHttpRequest(locationUrl, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "获取Location信息失败onFailure", Toast.LENGTH_LONG).show();
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Location location = handleLocationResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if ((location.getLocation() != null) ) {

                            String weatherId = showLocationInfo(location);
                            requestWeather(weatherId);
                        } else {
                            Toast.makeText(MainActivity.this, "查询失败，请确认输入的城市名格式正确！", Toast.LENGTH_SHORT).show();

                        }
                        swipeRefresh.setRefreshing(false);
                    }


                });

            }
        });
    }

    private String showLocationInfo(Location location){
        String id = location.getLocation().get(0).getId();
        return id;
    }


    private void showWeatherInfo(Weather weather) {
        String cityName = weather.getHeWeather6().get(0).getBasicX().getLocation();
        String updateTime = weather.getHeWeather6().get(0).getUpdate().getLoc();
        String degree=weather.getHeWeather6().get(0).getNowX().getTmp()+"℃";
        String weatherInfo=weather.getHeWeather6().get(0).getNowX().getCond_txt();
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        forecastLayout.removeAllViews();


        for(int i=0;i<3;i++ )
        {View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false);
        TextView dataText=(TextView) view.findViewById(R.id.data_text);
        TextView infoText=(TextView) view.findViewById(R.id.info_text);
        TextView maxText=(TextView)view.findViewById(R.id.max_text);
        TextView minText=(TextView)view.findViewById(R.id.min_text);

        dataText.setText(weather.getHeWeather6().get(0).getDaily_forecast().get(i).getDate());
        infoText.setText(weather.getHeWeather6().get(0).getDaily_forecast().get(i).getCond_txt_n());
        maxText.setText(weather.getHeWeather6().get(0).getDaily_forecast().get(i).getTmp_max());
        minText.setText(weather.getHeWeather6().get(0).getDaily_forecast().get(i).getTmp_min());
        forecastLayout.addView(view);
        }
    }
}